package com.book.shop.Webservice;

import com.book.shop.model.Book;
import com.book.shop.model.form.BookForm;
import com.book.shop.repository.BookRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

@Service
public class BookService {
    @Autowired
    public BookRepository bookRepository;

    //查找所有图书
    public List<Book> findAllBooks() {
        return bookRepository.findAll();
    }

    //查找指定图书
    public Book findBookById(Long bookId) {
        return bookRepository.findById(bookId).get();
    }

    //更新图书
    public Book updateBook(Book book) {
        return bookRepository.save(book);
    }

    //删除图书
    public void deleteBook(Book book) {
        bookRepository.delete(book);
    }

    //搜索图书
    public List<Book> searchBooks(String query) {
        return bookRepository.searchBooks("%" + query + "%");
    }

    //新增图书
    public Book saveBook(BookForm bookForm) {
        final Logger log = LoggerFactory.getLogger(BookService.class);
        byte[] image = null;
        byte[] imagebackup = null;
        final Book editBook;
        Book book = new Book();
        if (bookForm.getBookImage() != null) {
            try {
                image = bookForm.getBookImage().getBytes();
            } catch (IOException e) {
                log.error("Error occurred while getting bytes from book image", e);
            }
            if (image != null && image.length > 0) {
                book.setBookImage(image);
                book.setBookImageContentType("image/jpeg");
            }
        } else {
            if (bookForm.getBookId() != null) {
                editBook = bookRepository.findById(bookForm.getBookId()).get();
                imagebackup = editBook.getBookImage();
                book.setBookImage(imagebackup);
                book.setBookImageContentType("image/jpeg");
            }
        }
        book = bookForm.toBook(book);
        return bookRepository.save(book);
    }
}
